import { defineStore } from "pinia";
import { getLoginCodeAPI, postLoginAPI, postLoginCodeAPI, qqBindLoginAPI, QQLoginAPI, qqPatchLoginAPI, sendQQBindAPI, sendQQPathMsgAPI } from "@/api/user";
import { Profile, SourceEnum } from "@/types/user";
import useStore from "@/store";

export default defineStore("user", {
  state: () => {
    return {
      profile: {} as Profile,
    }
  },
  actions: {
    // 账户用户名密码登录
    async login (account: string, password: string) {
      const res = await postLoginAPI(account, password)
      this.profile = res.data.result
      // 合并购物车
      const { cartStore } = useStore();
      cartStore.mergeLocalCart()
    },

    // 发送验证码
    async sendMobileCode (mobile: string) {
      await getLoginCodeAPI(mobile)
    },

    // 手机号登录
    async mobileLogin (mobile: string, code: string) {
      const res = await postLoginCodeAPI({ mobile, code })
      this.profile = res.data.result
      // 合并购物车
      const { cartStore } = useStore();
      cartStore.mergeLocalCart()
    },

    // QQ 登录
    async qqLogin (unionId: string, source: SourceEnum) {
      const res = await QQLoginAPI({ unionId, source })
      this.profile = res.data.result
      // 合并购物车
      const { cartStore } = useStore();
      cartStore.mergeLocalCart()
    },

    // 绑定qq的短信验证码
    async sendQQBindMsg (mobile: string) {
      await sendQQBindAPI(mobile)
    },

    // qq 绑定登录
    async qqBindLogin (openId: string, mobile: string, code: string) {
      const res = await qqBindLoginAPI(openId, mobile, code)
      this.profile = res.data.result
      // 合并购物车
      const { cartStore } = useStore();
      cartStore.mergeLocalCart()
    },

    // 完善资料获取短信验证码
    async sendQQPathMsg (mobile: string) {
      await sendQQPathMsgAPI(mobile)
    },


    // 完善资料提交
    async qqPatchLogin (data: any) {
      const res = await qqPatchLoginAPI(data)
      // 1. 保存用户信息到 state 中
      this.profile = res.data.result
    },

    // 退出登录
    logout () {
      this.profile = {} as Profile
      // 清空本地存储
      localStorage.removeItem('profile')
      // 清空购物车
      const { cartStore } = useStore()
      cartStore.clearCart()
    }
  },
  // persist: true,  // 整个 store 现在将使用 默认的持久性设置进行保存。
  persist: {
    key: 'profile', //存储名称
    storage: localStorage, // 存储方式
    paths: ['profile'], //指定 state 中哪些数据需要被持久化。[] 表示不持久化任何状态，undefined 或 null 表示持久化整个 state
  } as {},
})